package cn.myframe;

import cn.myframe.utils.ssh.SSHMessage;
import cn.myframe.utils.ssh.SSHQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;

import javax.annotation.PostConstruct;
import javax.servlet.MultipartConfigElement;
import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * 程序启动类
 * 
 * @author  ynz
 * @email   ynz@myframe.cn
 * @version 创建时间：2018年6月7日 上午9:48:10
 */
@SpringBootApplication
//@EnableDubboConfiguration
@EnableScheduling
@EnableWebSocketMessageBroker
@EnableCaching
/*@EnableSwagger2*/
public class LeXiApplication {
	
	public static ApplicationContext ctx = null;
	
	public static void main(String[] args) {
		System.setProperty("spring.devtools.restart.enabled","false");
		ctx = SpringApplication.run(LeXiApplication.class, args);
		System.out.println("  _____ _______       _____ _______ ______ _____");
		System.out.println(" / ____|__   __|/\\   |  __ \\__   __|  ____|  __ \\  ");
		System.out.println("| (___    | |  /  \\  | |__) | | |  | |__  | |  | | ");
		System.out.println(" \\___ \\   | | / /\\ \\ |  _  /  | |  |  __| | |  | | ");
		System.out.println(" ____) |  | |/ ____ \\| | \\ \\  | |  | |____| |__| | ");
		System.out.println("|_____/   |_/_/    \\_\\_|  \\_\\ |_|  |______|_____/  ");
		
	}
	
	/**
     * 上传文件临时目录
     * Linux下有可能临时目录被删
     * @return
     */
    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        String location = System.getProperty("user.dir") + "/data/tmp";
        File tmpFile = new File(location);
        if (!tmpFile.exists()) {
            tmpFile.mkdirs();
        }
        factory.setLocation(location);
        return factory.createMultipartConfig();
    }

/*	@Bean("testCache")
	public CacheInterface cache(){
		ServiceLoader<CacheInterface> spiLoader = ServiceLoader.load(CacheInterface.class);
		Iterator<CacheInterface> iter = spiLoader.iterator();
		while (iter.hasNext()){
			return iter.next();
		}
		return null;

	}*/
    
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1
        corsConfiguration.addAllowedHeader("*"); // 2
        corsConfiguration.addAllowedMethod("*"); // 3
        return corsConfiguration;
    }

    /*@Bean*/
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }

    @Autowired
    private SimpMessagingTemplate messagingTemplate;


    /**
     * 推送SSH结果
     */
    @PostConstruct
    public void pushSSH(){
        ExecutorService executorService=Executors.newFixedThreadPool(2);
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        SSHMessage sshMsg = SSHQueue.getInstance().poll();
                        if(sshMsg!=null){
                            if(messagingTemplate!=null)
                                messagingTemplate.convertAndSend("/"+sshMsg.getTop(),sshMsg.getMsg());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        executorService.submit(runnable);
        executorService.submit(runnable);
    }


}
